const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const bodyParser = require('body-parser')
const mongoose = require('mongoose');


const uploads = require('./routes/public')
const writerRouter = require('./routes/writers')
const usersRouter = require('./routes/users');
const booksRouter = require('./routes/books')
const api = require('./routes/api');
const sendEmailRouter = require('./routes/sendEmail')
const adminRouter = require("./routes/admins")
const homeRouter = require("./routes/home")
const dataRouter = require("./routes/data")
const pingRouter = require("./routes/pingluns")

const app = express();

const port = 3000
//解决跨域
app.all('/*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, mytoken')
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, Authorization')
  res.setHeader('Content-Type', 'application/json;charset=utf-8')
  res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization, Accept,X-Requested-With')
  res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
  res.header('X-Powered-By', ' 3.2.1')
  if (req.method == 'OPTIONS') res.send(200)
  /*让options请求快速返回*/ else next()
})
// view engine setup

//使用body中间件
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

//使用mongoose中间件
const db = require("./db/db").mongoURL;
mongoose.connect(db)
  .then(() => console.log("success"))
  .catch(err => console.log(err))


//作者路由
app.use('/writers', writerRouter);

//用户路由
app.use('/users', usersRouter)

//管理员
app.use("/admins",adminRouter)

//静态资源
app.use('/uploads', express.static('uploads'));

//书籍路由
app.use('/books', booksRouter)

//上传图片
app.use("/api", api);

//发送邮件
app.use("/sendEmail", sendEmailRouter)

//推荐
app.use("/home", homeRouter);

//相关数据
app.use("/data", dataRouter);

//评论
app.use("/ping",pingRouter)
app.listen(port, () => console.log(`Example app listening on port port!`))
